package com.winit.openapi.erp.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.SearchOperator;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.query.filter.SearchFilterHelper;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.order.BPartnerImporterService;
import com.winit.erp.spi.order.OrderService;
import com.winit.erp.spi.order.SalesVATService;
import com.winit.erp.spi.order.command.ImporterCommand;
import com.winit.erp.spi.order.command.QueryOrderCommand;
import com.winit.erp.spi.order.command.SalesVATCommand;
import com.winit.erp.spi.order.command.UpdateOrderCommand;
import com.winit.erp.spi.order.vo.BPartnerImporter;
import com.winit.erp.spi.order.vo.Order;
import com.winit.erp.spi.order.vo.SalesVAT;
import com.winit.erp.spi.product.command.QueryProductCommand;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;

/**
 * @author ping.peng 2015-2-9 上午9:41:51
 * @since 1.0
 */
@Controller
@RequestMapping(value = "/erp/order")
public class OrderController extends BaseController {

    @Resource
    private OrderService            erpOrderService;
    @Autowired
    private BPartnerImporterService bPartnerImporterService;
    @Autowired
    private SalesVATService         salesVATService;

    @RequestMapping(value = "/updateLoanId")
    public String updateLoanId(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            UpdateOrderCommand command = buildUpdateOrderCommand(json);
            erpOrderService.updateOrder(command);

            QueryOrderCommand orderCommand = new QueryOrderCommand();
            orderCommand.setDocumentNo(command.getDocumentNo());
            Order order = erpOrderService.findByDocument(orderCommand);

            /*
             * QueryOrderCommand orderCommand =new QueryOrderCommand();
             * orderCommand.setDocumentNo(command.getDocumentNo()); Order order
             * = null;//orderService.findByDocument(orderCommand); List<Order>
             * list = orderService.findGood(orderCommand); for (Order order2 :
             * list) { QueryProductCommand queryProductCommand =new
             * QueryProductCommand();
             * queryProductCommand.setCode(order2.getGoodCode());
             * queryProductCommand.setSpecification(order2.getSpecification());
             * if(command.getCtx()==null) {
             * queryProductCommand.setAdLanguage("zh_CN"); }else {
             * queryProductCommand
             * .setAdLanguage(command.getCtx().getLanguageCountry()); }
             * queryProductCommand.setBpartnerId(order2.getBpartnerId());
             * List<Order> orderList =
             * orderService.findByGood(queryProductCommand); if(orderList==null
             * || orderList.size()<=0) { continue; } Long item = 0l; for (Order
             * order3 : orderList) { item += order3.getItemCount(); }
             * UpdateLoanLineCommand cmd = new UpdateLoanLineCommand();
             * cmd.setFspLoansLineId(command.getLoanId());
             * cmd.setGoodCode(order2.getGoodCode());
             * cmd.setSpecification(order2.getSpecification());
             * cmd.setStockInQty(item); loanService.updateLoansLine(cmd);
             * order=order2; }
             */
            Long orderId = 1l;
            if (order != null) orderId = order.getOrderId();
            responseMsg.setData(orderId);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    @RequestMapping(value = "/querySalesVAT")
    public String querySalesVAT(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            SalesVATCommand command = new SalesVATCommand();
            command.setBpartnerId(json.getLong("bpartnerId"));
            List<SalesVAT> list = salesVATService.querySalesVAT(command);
            responseMsg.setData(list);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    @RequestMapping(value = "/queryImporter")
    public String queryImporter(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ImporterCommand command = new ImporterCommand();
            command.setWarehouseId(json.getLong("warehouseId"));
            command.setBpartnerId(json.getLong("bpartnerId"));
            List<BPartnerImporter> list = bPartnerImporterService.queryImporter(command);
            responseMsg.setData(list);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    @RequestMapping(value = "/queryByGood")
    public String queryByGood(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            QueryProductCommand command = new QueryProductCommand();
            command.setCode(json.getString("code"));
            command.setSpecification(json.getString("specification"));
            command.setLoanId(json.getLong("loanId"));
            if (command.getCtx() == null) {
                command.setAdLanguage("zh_CN");
            } else {
                command.setAdLanguage(command.getCtx().getLanguageCountry());
            }
            command.setBpartnerId(json.getLong("bpartnerId"));

            List<Order> list = erpOrderService.findByGood(command);
            responseMsg.setData(list);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    @RequestMapping(value = "/queryOrder")
    public String queryOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        JSONObject json = (JSONObject) obj;
        Searchable searchable = Searchable.newSearchable();
        searchable.setPage(ApiConstant.PAGE_NO_DEFAULT - 1, ApiConstant.PAGE_SIZE_DEFAULT);
        searchable.addSort(new Sort(Direction.DESC, "C.updated"));
        searchable.and(SearchFilterHelper.newCondition("MP.VALUE", SearchOperator.eq, json.getString("productCode")));
        searchable.and(SearchFilterHelper.newCondition("C.loansId", SearchOperator.eq, json.getLong("loansId")));
        searchable.and(SearchFilterHelper.newCondition("RLT.AD_LANGUAGE", SearchOperator.eq, requestMsg.getLanguage()));
        searchable.and(SearchFilterHelper.newCondition("RL.AD_REFERENCE_ID", SearchOperator.eq, 1000064));

        QueryOrderCommand command = new QueryOrderCommand();
        command.setSearchable(searchable);
        Page<Order> pagelist = erpOrderService.queryOrderPage(command);

        if (pagelist != null) {
            responseMsg.setData(pagelist.getContent());
        }

        return SUCCESS;
    }

//    private CreateOrderCommand buildCreateOrderCommand(JSONObject json) {
//        CreateOrderCommand command = new CreateOrderCommand();
//        command.setCtx(CommandContext.getContext());
//        command.setCreatedby(Long.parseLong(CommandContext.getContext().getUserId()));
//        command.setUpdatedby(Long.parseLong(CommandContext.getContext().getUserId()));
//        command.setStatus(EnumOrderStatus.DR.getKey());
//        if (json.containsKey("orderId")) {
//            command.setOrderId(json.getLong("orderId"));
//        }
//        if (json.containsKey("clientId")) {
//            command.setClientId(json.getLong("clientId"));
//        } else {
//            command.setClientId(11L);
//        }
//        if (json.containsKey("orgId")) {
//            command.setOrgId(json.getLong("orgId"));
//        } else {
//            command.setOrgId(0L);
//        }
//        if (json.containsKey("bpartnerId")) {
//            command.setBpartnerId(json.getLong("bpartnerId"));
//        }
//        if (json.containsKey("warehouseId")) {
//            command.setWarehouseId(json.getLong("warehouseId"));
//        }
//        if (json.containsKey("destination")) {
//            command.setDestination(json.getString("destination"));
//        }
//        if (json.containsKey("transportmodeId")) {
//            command.setTransportmodeId(json.getLong("transportmodeId"));
//        }
//        if (json.containsKey("loansId")) {
//            command.setLoansId(json.getLong("loansId"));
//        }
//
//        return command;
//    }

    private UpdateOrderCommand buildUpdateOrderCommand(JSONObject json) {
        UpdateOrderCommand command = new UpdateOrderCommand();
        command.setCtx(CommandContext.getContext());
        command.setUpdatedby(Long.parseLong(CommandContext.getContext().getUserId()));

        if (json.containsKey("documentNo")) {
            command.setDocumentNo(json.getString("documentNo"));
        }
        if (json.containsKey("loanId")) {
            command.setLoanId(json.getLong("loanId"));
        }
        if (json.containsKey("orderId")) {
            command.setOrderId(json.getLong("orderId"));
        }

        return command;
    }

}
